/**
 *	The NeuroCoSA Toolkit
 *	Copyright (C) 2003-6 Stuart Meikle.
 *
 *	This is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation; either
 *	version 2.1 of the License, or (at your option) any later version.
 *
 *	This library is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *	Lesser General Public License for more details.
 *
 * @author	Stuart Meikle
 * @version	2006-halloween(mk2)
 * @license	LGPL
 */
package org.stumeikle.NeuroCoSA.PubSub;
import java.io.*;
import java.util.*;


/** 
 * publish and subscribe mechanisms for NeuroCoSA mk2
 * all new. could be a separate package in future. 
 * Needs synchronisation adding if its to be used cross thread in future. 
 * stumeikle 20061024
 *
 */
public class InfoService
{
    //list of published info
    LinkedList< Publication > 	iPubs;		//could be a hash really
    static int			iPubCount;	//static. otherwise publications
						//added to multiple info services get ids
						//messed up.

    public InfoService()
    {
	iPubs = new LinkedList< Publication > ();
	iPubCount = 0;
    }

    public LinkedList<Publication> getPublications()
    { return iPubs; }

    public void	addPublication( Publication p )
    {
	if (p==null)	return;

	//assign an id if the publication does not already have one
	if (p.getID()==0)
	{
	    iPubCount ++;
	    p.setID( iPubCount );
	}
	iPubs.add(p);
    }

    public void removePublication( Publication p )
    {
	iPubs.remove(p);
    }

    public int	getNumPublications()
    { return iPubCount; }

    public long subscribeTo( long id, Subscriber s )
    {
	//find a publication which matches id and subscribe
	ListIterator	i = iPubs.listIterator();
	for(;i.hasNext();)
	{
	    Publication	 p = (Publication) i.next();

	    if (p.getID()==id)
	    {
	        return p.subscribe(s);
	    }
	}

	return -1;
    }

    /* from EG directory
    public static void	main( String[] argv)
    {
	//create an info service - live newspaper headlines
	StockMarket	amsterdam = new StockMarket();

	//create a something to watch the data
	Trader		tim = new Trader();
	tim.setStockMarket( amsterdam );
	
	amsterdam.changes();
    }
    */
}
